import java.sql.*;

/**
 * 数据库连接工具类
 *
 * @author Chova
 * @date 2022/05/31
 */
public class DBUtil {

    private static final String JdbcDriver = "com.mysql.jdbc.Driver";
    private static final String Url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimeZone=UTC";
    private static final String Username = "crrcdt";
    private static final String Password = "crrcdt@2022";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        String sql;

        try {
            // 1. 加载JDBC驱动程序
            Class.forName(JdbcDriver);
            // 2. 获取数据库连接
            conn = DriverManager.getConnection(Url, Username, Password);
            // 3. 执行数据库操作
            stmt = conn.createStatement();
            sql = "select * from user";
            // 4. 执行SQL语句
            ResultSet rs = stmt.executeQuery(sql);

            // 5. 输出结果集
            while (rs.next()) {
                System.out.println(rs.getString("user_name") + "," + rs.getInt("user_no"));
            }

            // 6. 关闭数据库连接
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            try {
                if (null != stmt) {
                    stmt.close();
                }
            } catch (SQLException stmtE){
                throw new RuntimeException(stmtE);
            }
            try {
                if (null != conn) {
                    conn.close();
                }
            } catch (SQLException connE){
                throw new RuntimeException(connE);
            }
        }
        System.out.println("\n数据库操作执行成功!");
    }
}
